import {Directive, EventEmitter, Input, Optional, Output} from "@angular/core";
import {FormBuilder, FormGroup} from "@angular/forms";
import {Validators} from "../validator/Validators";
import {Error} from "../api/Error";
import {DynamicDialogRef, MessageService} from "primeng/api";
import {HttpClient} from "@angular/common/http";
import {ErrorService} from "../api/ErrorService";

@Directive({
  selector: '[gnForm]'
})
export class FormDirective {

  formGroup: FormGroup;
  validators = new Validators();

  @Input() customSubmit = false;
  @Input() successMessage: string;
  @Input() url: string;

  @Output() onSubmitted = new EventEmitter<any>();
  @Output() onSubmitError = new EventEmitter<Error>();
  @Output() onSubmit = new EventEmitter<any>();

  constructor(formBuilder: FormBuilder,
              @Optional() dialogRef: DynamicDialogRef,
              private httpClient: HttpClient,
              private messageService: MessageService,
              private errorService: ErrorService) {
    this.formGroup = formBuilder.group({});

    if (dialogRef) {
      this.onSubmitted.subscribe(value => {
        dialogRef.close(value);
      });
    }
  }

  loadValue(id: string): void {
    this.httpClient.get(this.url + "/" + id)
      .subscribe((data) => {
          this.formGroup.patchValue(data);
        },
        (error) => {
          const submitError = {
            message: "获取数据错误",
            error: error,
            data: id
          };
          this.onSubmitError.emit(submitError);
          this.errorService.occur(submitError);
        });
  }

  preSubmit = async function (value: any): Promise<void> {
  };

  async submit() {
    if (!this.customSubmit) {
      const value = this.formGroup.value;
      await this.preSubmit(value);
      this.onSubmit.emit(value);
      this.httpClient.put(this.url, value)
        .subscribe(() => {
            this.messageService.add({
              severity: 'success',
              summary: '成功',
              detail: this.successMessage || '信息已保存'
            });
            this.onSubmitted.emit(value);
          },
          (error) => {
            const submitError = {
              message: "处理错误",
              error: error,
              data: value
            };
            this.onSubmitError.emit(submitError);
            this.errorService.occur(submitError);
          });
    }
  }

}
